package com.mark.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import com.alibaba.fastjson.JSON;
import com.mark.entity.AccessToken;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * 完成微信获取access_token 获取
 *
 * @author mark
 */
public class AccessTokenUtils {
    //生成日志对象
    static Logger log = Logger.getLogger(AccessTokenUtils.class);

    public static String getOrRefreshAccessToken() {
        //读取appid
        String appid = ConfigManager.getString("APPID", "APPID");
        String secret = ConfigManager.getString("APPSRECT", "123456");

        String encrypt = MacUtils.decrypt("#mark_wx", appid);
        String encrypt2 = MacUtils.decrypt("#mark_wx", secret);
        String reqUrl = ConfigManager.getString("BASE_URL", "https://api.weixin.qq.com/cgi-bin/")+"token";
        String grant_type = ConfigManager.getString("grant_type","client_credential");
        String url = String.format("%s?grant_type=%s&appid=%s&secret=%s", reqUrl,grant_type,
                encrypt, encrypt2);
        HttpURLConnection http = null;
        AccessToken accessToken = null;
        try {
            log.info("开始获取accesss_token ");
            URL urlGet = new URL(url);
            http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");      //必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

            http.connect();
            log.info("获取accesstken结束");
            //获取Response 输入流数据
            InputStream httpin = http.getInputStream();
            int size = httpin.available();
            //定义字节数组
            byte[] jsonBytes = new byte[size];
            //
            httpin.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            accessToken = JSON.parseObject(message,AccessToken.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken.getAccess_token();
    }

    public static void main(String[] args) {
        String accessToken = getOrRefreshAccessToken();
        System.out.println(accessToken);
    }
}
